package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.SimpleDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DynamicConfigLab;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerRelationDepartmentDetail;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 客户部门信息 编辑
 *
 * @author wu
 */

public class CustomerRelationDepartmentInfoEditFragment extends BaseFragment {

  //public static final String EXTRA_DATA = "com.isunland.managesystem.ui.extra_data";
  protected static final String TAG = CustomerRelationDepartmentInfoEditFragment.class.getName();
  //protected static final int REQUEST_DIRCT_DEPARTMENT = 2;// 上级部门
  protected static final int REQUEST_CLEAR_DIRCT_MANAGER = 3;
  protected static final int REQUEST_CLEAR__MANAGER = 4;// 上级部门
  //protected static final int REQUEST_CLEAR_DEPARTMENT = 5;
  private static final int REQUEST_MANAGER = 1;
  private static final int REQUEST_DIRCT_MANAGER = 0;
  //private BaseVolleyActivity mActivity;
  HashMap<String, String> mDepartmentDetail;
  //private TextView mEtSuperDepartmentEdit;// 上级部门
  private EditText etNameDepartmentEdit;// 部门名称
  private EditText mEtDpartmentManagerEdit;// 部门经理
  private ImageView mAddDpartmentManagerEditCustomerRelation;
  private EditText mEtDpartmentIndirectManagerEdit;// 主管领导
  private ImageView mDddDpartmentIndirectManagerEditCustomerRelation;
  private EditText etDpartmentDutyEdit;// 职责说明
  @SuppressWarnings("unused") private String mManagerId;
  @SuppressWarnings("unused") private String mDirictManagerId;
  //private String mSuperDepartmentId;
  private String mOrgName;
  private String mManagerName;
  private String mDirectorName;
  private String mDutyDescript;
  //private String mPName;// 上级部门

  //public static Fragment newInstance(CustomerRelationDepartmentDetail mDepartMentDetailInfo) {
  //
  //  Bundle bundle = new Bundle();
  //  bundle.putSerializable(EXTRA_DATA, mDepartMentDetailInfo);
  //  CustomerRelationDepartmentInfoEditFragment fragment =
  //      new CustomerRelationDepartmentInfoEditFragment();
  //  fragment.setArguments(bundle);
  //  return fragment;
  //}

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    setTitleCustom(R.string.departmentInfoEdit);
    //CustomerRelationDepartmentDetail mDepartment =
    //		(CustomerRelationDepartmentDetail) getArguments().getSerializable(EXTRA_DATA);
    mManagerId =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.MANAGERID, "");
    mDirictManagerId =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DIRECTORID, "");
    //mSuperDepartmentId =
    //    SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.PID, "");
    mOrgName =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DEPARTMENT_NAME, "");
    mOrgName = CustomerRelationDepartmentDetail.getDirectDepartment(mOrgName);

    mManagerName =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.MANAGER_NAME, "");
    mDirectorName =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DIRECTOR_NAME, "");
    //mPName = SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.PNAME, "");
    mDutyDescript =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DUTYSCRIPT, "");
    //String mCustomerName =
    //		SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.CUSTOMER_NAME, "");

  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_department_info_edit, container, false);
    //mEtSuperDepartmentEdit =
    //    (TextView) view.findViewById(R.id.et_superDepartment_edit_CustomerRelation);

    etNameDepartmentEdit =
        (EditText) view.findViewById(R.id.et_nameDepartment_edit_CustomerRelation);
    mEtDpartmentManagerEdit =
        (EditText) view.findViewById(R.id.et_dpartmentManager_edit_CustomerRelation);
    mAddDpartmentManagerEditCustomerRelation =
        (ImageView) view.findViewById(R.id.et_addDpartmentManager_edit_CustomerRelation);
    mEtDpartmentIndirectManagerEdit =
        (EditText) view.findViewById(R.id.et_dpartmentIndirectManager_edit_CustomerRelation);
    mDddDpartmentIndirectManagerEditCustomerRelation =
        (ImageView) view.findViewById(R.id.et_addDpartmentIndirectManager_edit_CustomerRelation);
    etDpartmentDutyEdit = (EditText) view.findViewById(R.id.et_dpartmentDuty_edit_CustomerRelation);

    initDataCustomer();
    DynamicConfigLab config =
        DynamicConfigLab.newInstance(mActivity, getString(R.string.module_deptColumns));
    config.autoConfigTitle(view);
    config.autoConfigVisiblity(view);
    return view;
  }

  private void initDataCustomer() {
    etNameDepartmentEdit.setText(mOrgName);
    mEtDpartmentManagerEdit.setText(mManagerName);
    mAddDpartmentManagerEditCustomerRelation.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        if (TextUtils.isEmpty(mEtDpartmentManagerEdit.getText().toString().trim())) {

          showDialog(REQUEST_MANAGER);
        } else {
          showDialog(REQUEST_CLEAR__MANAGER);
        }
      }
    });
    mEtDpartmentIndirectManagerEdit.setText(mDirectorName);
    mDddDpartmentIndirectManagerEditCustomerRelation.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        if (TextUtils.isEmpty(mEtDpartmentIndirectManagerEdit.getText().toString().trim())) {

          showDialog(REQUEST_DIRCT_MANAGER);
        } else {
          showDialog(REQUEST_CLEAR_DIRCT_MANAGER);
        }
      }
    });

    //mEtSuperDepartmentEdit.setText(mPName);
    //mEtSuperDepartmentEdit.setOnClickListener(new OnClickListener() {
    //
    //  @Override public void onClick(View v) {
    //    if (TextUtils.isEmpty(mEtSuperDepartmentEdit.getText().toString().trim())) {
    //
    //      showDialog(REQUEST_DIRCT_DEPARTMENT);
    //    } else {
    //      showDialog(REQUEST_CLEAR_DEPARTMENT);
    //    }
    //  }
    //});
    etDpartmentDutyEdit.setText(mDutyDescript);
  }

  private void showDialog(int type) {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (type) {
      case REQUEST_MANAGER:
        dialog = new CustomerMemberDialogFragment();
        break;
      case REQUEST_DIRCT_MANAGER:
        dialog = new CustomerMemberDialogFragment();
        break;
      //case REQUEST_DIRCT_DEPARTMENT:
      //  dialog = new CustomerRelationSuperDepartmentDialogFragment();
      //  break;
      case REQUEST_CLEAR__MANAGER:
        dialog = SimpleDialogFragment.newInstance(R.string.chooseOperation, R.string.edit, 0,
            R.string.clearChoose);
        break;
      case REQUEST_CLEAR_DIRCT_MANAGER:
        dialog = SimpleDialogFragment.newInstance(R.string.chooseOperation, R.string.edit, 0,
            R.string.clearChoose);
        break;
      //case REQUEST_CLEAR_DEPARTMENT:
      //  dialog = SimpleDialogFragment.newInstance(R.string.chooseOperation, R.string.edit, 0,
      //      R.string.clearChoose);
      //  break;

      default:
        return;
    }
    dialog.setTargetFragment(CustomerRelationDepartmentInfoEditFragment.this, type);
    dialog.show(fm, "");
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_confirm:
        volleyPostSave();
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DEPARTMENT_SAVE);
    mDepartmentDetail = new HashMap<>();
    String id =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DEPARTMENTID, null);
    LogUtil.i(TAG, "id<<<<<<<<<<" + id);
    String orgCode =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DEPARTMENT_CODE, null);
    LogUtil.i(TAG, "orgCode<<<<<<<<<<" + orgCode);
    String orgName = etNameDepartmentEdit.getText().toString();

    String dutyDescript = etDpartmentDutyEdit.getText().toString();
    String customerName =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.CUSTOMER_NAME, null);
    LogUtil.i(TAG, "customerName<<<<<<<<<<" + customerName);
    String customerId =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.CUSTOMER_ID, "");
    LogUtil.i(TAG, "customerId<<<<<<<<<<" + customerId);
    String managerName = mEtDpartmentManagerEdit.getText().toString().trim();
    String directorName = mEtDpartmentIndirectManagerEdit.getText().toString();

    mDepartmentDetail.put("id", id);
    mDepartmentDetail.put("orgCode", orgCode);
    mDepartmentDetail.put("orgName", orgName);
    //mDepartmentDetail.put("pid", mSuperDepartmentId);
    mDepartmentDetail.put("dutyDescript", dutyDescript);
    mDepartmentDetail.put("customerName", customerName);
    mDepartmentDetail.put("customerId", customerId);
    //		mDepartmentDetail.put("managerId", mManagerId);
    mDepartmentDetail.put("managerName", managerName);
    //		mDepartmentDetail.put("directorId", mDirictManagerId);
    mDepartmentDetail.put("directorName", directorName);

    LogUtil.i(TAG, "params=" + mDepartmentDetail.toString());

    mActivity.volleyPost(url, mDepartmentDetail, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    switch (requestCode) {
      case REQUEST_MANAGER:
        CustomerDialog result =
            (CustomerDialog) data.getSerializableExtra(CustomerMemberDialogFragment.EXTRA_VALUE);
        mEtDpartmentManagerEdit.setText(result.getName());
        mManagerId = result.getId();
        break;
      case REQUEST_CLEAR__MANAGER:
        int choice = data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE,
            SimpleDialogFragment.VALUE_POSITIVE);
        if (choice == SimpleDialogFragment.VALUE_POSITIVE) {
          showDialog(REQUEST_MANAGER);
        } else {
          mEtDpartmentManagerEdit.setText("");
          mManagerId = "";
        }
        break;
      case REQUEST_DIRCT_MANAGER:
        CustomerDialog result1 =
            (CustomerDialog) data.getSerializableExtra(CustomerMemberDialogFragment.EXTRA_VALUE);
        mEtDpartmentIndirectManagerEdit.setText(result1.getName());
        mDirictManagerId = result1.getId();
        break;
      case REQUEST_CLEAR_DIRCT_MANAGER:
        int choice2 = data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE,
            SimpleDialogFragment.VALUE_POSITIVE);
        if (choice2 == SimpleDialogFragment.VALUE_POSITIVE) {
          showDialog(REQUEST_DIRCT_MANAGER);
        } else {
          mEtDpartmentIndirectManagerEdit.setText("");
          mDirictManagerId = "";
        }
        break;
      //case REQUEST_DIRCT_DEPARTMENT:
      //  CustomerDialog result2 =
      //      (CustomerDialog) data.getSerializableExtra(CustomerMemberDialogFragment.EXTRA_VALUE);
      //  mOrgName = result2.getName();
      //  mOrgName = CustomerRelationDepartmentDetail.getDirectDepartment(mOrgName);
      //  mEtSuperDepartmentEdit.setText(mOrgName);
      //  mSuperDepartmentId = result2.getId();
      //  break;
      //case REQUEST_CLEAR_DEPARTMENT:
      //  int choice3 = data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE,
      //      SimpleDialogFragment.VALUE_POSITIVE);
      //  if (choice3 == SimpleDialogFragment.VALUE_POSITIVE) {
      //    showDialog(REQUEST_DIRCT_DEPARTMENT);
      //  } else {
      //    mEtSuperDepartmentEdit.setText("");
      //    mSuperDepartmentId = "";
      //  }
      //  break;
      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
